package com.myspace.view.user;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.context.WebApplicationContext;

import com.myspace.common.exception.ApplicationException;
import com.myspace.common.exception.UserNotFoundException;
import com.myspace.domain.User;
import com.myspace.service.user.UserService;
import com.myspace.view.common.Constant;
import com.myspace.view.common.DispatchBaseAction;

public class UserAction extends DispatchBaseAction {

	public ActionForward login(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		WebApplicationContext wc = this.getWebApplicationContext();
		UserService us = (UserService) wc.getBean("userService");
		UserForm uf = (UserForm) form;
		try {
			User user = us.login(uf.getUser());
			HttpSession session = request.getSession();
			session.setAttribute(Constant.USER, user);
		} catch (ApplicationException e) {
			ActionMessages errors = new ActionMessages();
			if (e instanceof UserNotFoundException)
				errors.add("user.name", new ActionMessage("用户不存在!", false));
			else
				errors.add("user.password", new ActionMessage("密码不正确!", false));
			this.saveErrors(request, errors);
			return mapping.getInputForward();
		}
		return mapping.findForward("success");
	}

	public ActionForward logout(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		request.getSession().invalidate();
		return mapping.findForward("index");
	}

	public ActionForward register(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ActionForward forward = mapping.findForward("success");
		WebApplicationContext wc = this.getWebApplicationContext();
		UserService us = (UserService) wc.getBean("userService");
		UserForm uf = (UserForm) form;
		User us1 = uf.getUser();
		try {
			User user = us.register(us1);
			us1.setUpdateDate(new Date());
			HttpSession session = request.getSession();
			session.setAttribute(Constant.USER, user);
		} catch (DataIntegrityViolationException e) {
			getLogger().info("User has existed!");
			ActionMessages errors = new ActionMessages();
			errors.add("userName", new ActionMessage("用户名已经存在！", false));
			this.saveErrors(request, errors);
			return mapping.getInputForward();
		}
		return forward;
	}
}